package com.lemt.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lemt.mall.entity.Category;
import com.lemt.mall.entity.Goods;
import com.lemt.mall.entity.GoodsCategory;
import com.lemt.mall.entity.Inventory;
import com.lemt.mall.entity.vo.GoodsVo;
import com.lemt.mall.mapper.CategoryMapper;
import com.lemt.mall.mapper.GoodsCategoryMapper;
import com.lemt.mall.mapper.GoodsMapper;
import com.lemt.mall.mapper.InventoryMapper;
import com.lemt.mall.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zik
 * @since 2023-09-10
 */
@Slf4j
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public Boolean saveGoods(GoodsVo goodsVo) {


        Goods goods = new Goods();
        // 复制goods
        copyProperties(goodsVo,goods);
        log.info("goods => {}" ,goods);
        // 获取分类
        List<Category> categories = goodsVo.getCategories();
        log.info("categoryList => {}",categories);
        // 获取库存
        List<Inventory> inventories = goodsVo.getInventories();
        log.info("inventories = {}",inventories);


        // 添加商品基本信息到mysql
        if (goodsMapper.insert(goods) != 1){
            return false;
        }
        // 获取刚刚添加的商品信息
        Goods goods1 = goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getGoodsName, goods.getGoodsName()));

        log.info("将分类信息分别添加到对照表中-》");
        for (Category category : categories){
            goodsCategoryMapper.insert(new GoodsCategory(null,goods1.getId(),category.getId()));
        }

        log.info("将库存信息添加到对应表中");
        for (Inventory inventory : inventories){
            inventoryMapper.insert(new Inventory(null,goods1.getId(),inventory.getRepoName(),inventory.getInventory(),null));
        }
        return true;
    }

    @Override
    public String removeGoodsById(Integer id) {

        // 删除对应分类
        log.info("查找对应商品");
        goodsCategoryMapper.delete(new LambdaQueryWrapper<GoodsCategory>().eq(GoodsCategory::getGoodsId,id));

        // 删除对应库存
        log.info("删除对应库存");

        inventoryMapper.delete(new LambdaQueryWrapper<Inventory>().eq(Inventory::getGoodsId,id));
        // 删除图片（封面与banner）

        // 删除商品
        log.info("删除商品");
        goodsMapper.deleteById(id);
        return "删除成功";
    }

    @Override
    public Map<String, Object> getList(Integer page, Integer pageSize, String name) {

        log.info("name=>{}",name);
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!Strings.isEmpty(name), Goods::getGoodsName, name).orderByDesc(Goods::getUpdateTime);

        IPage<Goods> pageGoods = goodsMapper.selectPage(new Page<>(page,pageSize),queryWrapper);
        //总记录数
        long totalCount = pageGoods.getTotal();
        //总页数
        long totalPage = pageGoods.getPages();
        //当前页
        long currentPage = pageGoods.getCurrent();
        //每页记录数
        long size = pageGoods.getSize();
        List<GoodsVo> goodsVos = new ArrayList<>();
        //每页数据集合
        List<Goods> goods = pageGoods.getRecords();

        goods.forEach(item -> goodsVos.add(getCategoryInventory(item)));
        log.info(goodsVos.toString());

        //封装返回数据
        Map<String,Object> map = new HashMap<>();
        map.put("totalCount",totalCount);
        map.put("totalPage",totalPage);
        map.put("currentPage",currentPage);
        map.put("size",size);
        map.put("records",goodsVos);
        return map;
    }


    public GoodsVo getCategoryInventory(Goods goods) {

        GoodsVo goodsVo = new GoodsVo();
        copyProperties(goods,goodsVo);
        log.info("{}",goodsVo);
        List<GoodsCategory> goodsCategories = goodsCategoryMapper.selectList(new LambdaQueryWrapper<GoodsCategory>().eq(GoodsCategory::getGoodsId, goods.getId()));
        List<Category> categories = new ArrayList<>();

        goodsCategories.forEach(goodsCategory -> {
            categories.add(categoryMapper.selectById(goodsCategory.getCategoryId()));
        });

        goodsVo.setCategories(categories);

        List<Inventory> inventories = inventoryMapper.selectList(new LambdaQueryWrapper<Inventory>().eq(Inventory::getGoodsId, goods.getId()));
        goodsVo.setInventories(inventories);
        return goodsVo;
    }
}
